package Meter::Email;

#===============================================================================
#     REVISION:  $Id: Email.pm 100 2011-07-19 16:24:50Z xdr.box@gmail.com $
#  DESCRIPTION:  Wrapper class for sending email notifications
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 100 $) [1];

use English qw( -no_match_vars );
use Params::Validate qw(:all);
use Net::SMTP;
use MIME::Lite;
use Carp;

#use Smart::Comments;

use Meter::Config;
use Meter::Log;
use Meter::LogParams;

use base qw(Exporter);

our @EXPORT_OK = qw(
    send_email
);

sub send_email : Log( result => 0 ) {
    my %params = validate(
        @_,
        {   to      => 1,
            subject => 1,
            text    => 1,
        }
    );

    my $logger = get_logger();
    my $config = get_config();

    if ( $config->{'email'}{'disable'} ) {
        $logger->warn('Email sending is disabled');
        return;
    }

    my $smtp = Net::SMTP->new( %{ $config->{'email'}{'net_smtp_options'} } )
        or confess 'Cannot instantiate Net::SMTP object';

    $smtp->mail( $config->{'email'}{'from_address'} )
        or confess 'SMTP error on MAIL FROM phase';

    $smtp->to( $params{'to'} )
        or confess 'SMTP error on RCPT TO phase';

    $smtp->data()
        or confess 'SMTP error on DATA phase';

    my $msg = MIME::Lite->new(
        From     => $config->{'email'}{'from_address'},
        To       => $params{'to'},
        Subject  => $params{'subject'},
        Data     => $params{'text'},
        'Type'   => 'text/plain',
        Encoding => 'base64',
    );
    $msg->attr( 'content-type.charset' => 'UTF8' );
    my $str = $msg->as_string();
    ### str: $str

    $smtp->datasend($str)
        or confess 'SMTP error on datasend()';
    $smtp->dataend()
        or confess 'SMTP error on dataend()';
    $smtp->quit()
        or confess 'SMTP error on QUIT phase';

    return;
}

1;
